<template>
  <!-- 报名详情页面的HTML结构 -->
  <div class="details-container page-container">
    <!-- 页面头部，包含返回按钮和赛事名称 -->
    <el-page-header title="返回" @back="handleBack">
      <!-- 页头内容插槽，显示赛事名称 -->
      <template #content>
        <h1 size="largez">{{ details_data.name }}报名入口</h1>
      </template>
    </el-page-header>
    <el-divider></el-divider>
    <!-- 赛事描述区域，使用Element Plus的描述列表组件 -->
    <div class="descriptions-container">
      <el-descriptions :column="2" border>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">赛事名称</div>
          </template>
          {{ details_data.name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">比赛地点</div>
          </template>
          {{ details_data.economizeName }},{{ details_data.marketName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报名时间</div>
          </template>
          {{ details_data.startTime }} 至 {{ details_data.endTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">赛事编号</div>
          </template>
          {{ details_data.eventNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">分组</div>
          </template>
          {{ group_name }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <!-- 参赛人员管理区域 -->
    <div class="content-container">
      <div class="content-heder-container">
        <el-text>参与参赛人员名单</el-text>
        <el-space>
          <el-input
            clearable
            v-model="query_data.studentName"
            placeholder="搜索姓名"
            size="large"
          ></el-input>
          <el-input
            clearable
            v-model="query_data.phone"
            size="large"
            placeholder="搜索手机号"
          ></el-input>
          <el-select
            v-model="query_data.entryState"
            size="large"
            placeholder="请选择参赛状态"
            clearable
          >
            <el-option label="待审核" :value="2"></el-option>
            <el-option label="待绑定" :value="3"></el-option>
            <el-option label="已绑定" :value="4"></el-option>
          </el-select>
          <el-button
            size="large"
            :icon="Search"
            circle
            :loading="loading"
            @click="() => handleLoad(true)"
          />
          <el-button type="primary" @click="handleOpenModal"
            >添加参赛人员</el-button
          >
        </el-space>
      </div>
      <el-table
        :data="data"
        border
        style="width: 100%"
        v-loading="loading"
        empty-text="未查询到已报名参赛人员"
      >
        <el-table-column label="学生ID" prop="studentId" width="80" />
        <el-table-column label="姓名" prop="studentName" width="100">
        </el-table-column>
        <el-table-column label="手机号码" prop="phone" width="120" />
        <el-table-column label="参赛证号" prop="entryNumber"> </el-table-column>
        <el-table-column label="指导老师">
          <template #default="scope">
            <TeacherSelect
              :modelValue="
                scope.row.teacherId ? Number(scope.row.teacherId) : null
              "
              @change="
                (value) => {
                  handleTecChange(value, scope.row);
                }
              "
            >
            </TeacherSelect>
          </template>
        </el-table-column>
        <el-table-column label="参赛状态" prop="entryState" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.entryState == 0" type="info" size="small">
              禁用
            </el-tag>
            <el-tag
              v-else-if="scope.row.entryState == 1"
              type="danger"
              size="small"
            >
              未报名
            </el-tag>
            <el-tag
              v-else-if="scope.row.entryState == 2"
              type="warning"
              size="small"
            >
              待审核
            </el-tag>
            <el-tag
              v-else-if="scope.row.entryState == 3"
              type="primary"
              size="small"
            >
              待绑定
            </el-tag>
            <el-tag
              v-else-if="scope.row.entryState == 4"
              type="success"
              size="small"
            >
              已绑定
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="Address" width="100">
          <template #default="scope">
            <el-dropdown
              trigger="click"
              @command="(value) => handleOperate(value, scope.row)"
              v-if="scope.row.entryState < 4"
            >
              <span class="el_dropdown_link">
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="remove-join"
                    v-if="scope.row.entryState == 2"
                  >
                    <el-icon> <Delete /> </el-icon>撤销报名</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="edit-id"
                    v-if="scope.row.entryState == 3"
                  >
                    <el-icon> <CircleClose /> </el-icon>填写ID码
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <template v-else>
              <el-button @click="handleOpenInfoModal(scope.row)"
                >查看准考证</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="total"
          @current-change="handlePage"
        />
      </div>
      <!-- 添加参赛人员的模态框 -->
      <NoJoinStudentsModal
        ref="NoJoinStudentsModalRef"
        :eventId="route.params.eventId"
        @closed="
          () => {
            handleLoad(true);
          }
        "
      />
    </div>
    <!-- 编辑ID码的模态框 -->
    <el-dialog title="激活" width="640px" v-model="edit_id_modal.show">
      <el-form label-width="96px">
        <el-form-item label="激活码">
          <el-input
            v-model="edit_id_modal.key"
            size="large"
            placeholder="请填写激活码"
          />
          <el-text>请输入激活码，激活码请向赛事组委会申请获得</el-text>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" @click="handleBindIdFroStudent"
            >确认激活码</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 准考证信息模态框 -->
    <AdmissionTicketInfoModal />
  </div>
</template>

<script  setup>
// 导入自定义的分页钩子
import { usePage } from "@/hooks/usePage";
// 导入赛事管理相关的API接口
import {
  GetRegisteredStudentsApi,
  GetEventInfoByEventIdApi,
  WithdrawalRegistrationApi,
  BindingTeacherApi,
  GetGroupsApi,
} from "@/api/manage/competition/index.js";
// 导入自定义的指导老师选择组件
import TeacherSelect from "@/components/teacher-select/index.vue";
// 导入Vue的响应式引用和生命周期钩子
import { ref, onMounted } from "vue";
// 导入Element Plus的搜索和删除图标
import { Search, Delete } from "@element-plus/icons-vue";
// 导入未报名学生模态框组件
import NoJoinStudentsModal from "./modal/no-join-students.vue";
// 导入Vue Router的路由钩子
import { useRoute, useRouter } from "vue-router";
// 导入Element Plus的消息框和确认框组件
import { ElMessage, ElMessageBox } from "element-plus";
// 导入激活码激活的API函数
import { ActivationKeyApi } from "@/api/index.js";
// 导入准考证信息模态框组件
import AdmissionTicketInfoModal from "@/components/admission-ticket-info-modal/index.vue";
// 导入自定义的模态框打开工具函数
import { open } from "@/utils/modal";
const route = useRoute(); // 获取当前路由信息
const router = useRouter(); // 获取路由实例
const NoJoinStudentsModalRef = ref(); // 定义未报名学生模态框的引用

// 使用分页钩子获取已报名学生列表和分页功能
const { total, data, loading, query_data, handleLoad, handlePage } = usePage({
  api_fn: GetRegisteredStudentsApi,
  q_data: {
    studentName: "",
    phone: "",
    eventId: route.params.eventId,
    entryState: "",
  },
});
const no_join_modal_show = ref(false);

// 打开未报名学生模态框的方法
const handleOpenModal = () => {
  NoJoinStudentsModalRef.value.handleOpenModal();
};
// 处理操作按钮的点击事件
const handleOperate = (command, row) => {
  // 打开编辑ID码模态框
  if (command == "edit-id") {
    edit_id_modal.value.key = "";
    edit_id_modal.value.studentId = row.studentId;
    edit_id_modal.value.show = true;
  } else if (command == "remove-join") {
    // 撤销报名
    ElMessageBox.confirm("是否撤销报名？", "提示", {
      "cancel-button-text": "取消",
      "confirm-button-text": "确定",
      type: "warning",
    }).then(async () => {
      // 调用API撤销报名，并根据响应更新消息和数据
      let res = await WithdrawalRegistrationApi({
        studentId: row.studentId,
        eventId: route.params.eventId,
        rootId: details_data.value.rootId,
      });
      if (!res.success) {
        ElMessage.error(res.message);
      } else {
        ElMessage.success(res.message);
      }
      handleLoad(true); // 重新加载数据
    });
  }
};

/**
 * 返回上一步
 */
const handleBack = () => {
  router.back();
};

// ----------- 获取详情 -----------
// 获取赛事详情和分组信息
const details_data = ref({});
const handleGetDetails = async () => {
  let res = await GetEventInfoByEventIdApi({
    eventId: route.params.eventId,
  });
  if (res.success) {
    details_data.value = res.entity;
    handleGetGroups();
  }
};
const group_name = ref("-");

const handleGetGroups = async () => {
  let res = await GetGroupsApi();
  if (res.success) {
    let find = res.entityList.find((item) => {
      return item.groupId == details_data.value.groupId;
    });
    if (find) {
      group_name.value = find.groupDescribe;
    }
  }
};

// ----------- id码 -----------
// 处理ID码绑定和指导老师变更
const edit_id_modal = ref({
  show: false,
  studentId: "",
  key: "",
});
/**
 * 绑定激活码
 */
const handleBindIdFroStudent = async () => {
  let res = await ActivationKeyApi({
    studentId: edit_id_modal.value.studentId,
    key: edit_id_modal.value.key,
    eventId: route.params.eventId,
  });
  if (res.success) {
    ElMessage.success(res.message);
    edit_id_modal.value.show = false;
    handleLoad(true);
  } else {
    ElMessage.error(res.message);
  }
};
// --------------------------------------------
/**
 * 切换指导老师
 */
const handleTecChange = async (value, row) => {
  let res = await BindingTeacherApi({
    studentId: row.studentId,
    teacherId: value,
    eventId: route.params.eventId,
  });
  if (res.success) {
    ElMessage.success(res.message);
    row.teacherId = value;
  } else {
    ElMessage.error(res.message);
  }
};

// 打开查看准考证的模态框
const handleOpenInfoModal = (data) => {
  open("admission-ticket-info", {
    ...data,
    eventId: route.params.eventId,
  });
};
// 组件挂载后执行的逻辑
onMounted(() => {
  handleLoad(true);
  handleGetDetails();
});
</script>

<style lang="scss" scoped>
.details-container {
  padding: 20px;
  box-sizing: border-box;

  .content-container {
    .content-heder-container {
      padding: 16px 0;
      display: flex;
      align-content: center;
      justify-content: space-between;
    }

    .pagination-container {
      display: flex;
      justify-content: center;
      padding: 32px 0;
    }
  }
}
:deep .el-select__selection {
  width: 192px !important;
}
</style>